# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         logkit_pro.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2021/1/12 下午8:27
# -------------------------------------------------------------------------------
import os

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

__all__ = ['LogkitProAPIView']


def read_file(file_path, index):
    with open(file_path, 'r', encoding='utf8') as f:
        result = []
        if not index:
            index = f.seek(0, 2) - 2000
        f.seek(index)
        for i in range(25):
            temp_result = f.readline().strip()
            if temp_result:
                result.append(temp_result)
        index = f.tell()
    data = os.linesep.join(result)
    if data:
        data += os.linesep
    return index, data


class LogkitProAPIView(APIView):

    def post(self, request, *args, **kwargs):
        base_dir = os.path.abspath(os.path.dirname(__file__)).split('apps')[0]
        logs_path = os.path.join(base_dir, 'logs')
        qaplatform_info_log_path = os.path.join(logs_path, 'QAPlatform_info.log')
        celery_worker_log_path = os.path.join(logs_path, 'celery-worker.log')

        request_data = request.data
        qaplatform_info_log_index = request_data.get('qaplatform_info_log_index', 0)
        celery_worker_log_index = request_data.get('celery_worker_log_index', 0)

        # 是否获取qaplatform_info_log日志，True：获取，False：不获取
        crawl_qaplatform_info_log = request_data.get('crawl_qaplatform_info_log', False)
        # 是否获取celery_worker_log日志，True：获取，False：不获取
        crawl_celery_worker_log = request_data.get('crawl_celery_worker_log', False)

        qaplatform_info_log = ''
        celery_worker_log = ''
        if crawl_qaplatform_info_log:
            qaplatform_info_log_index, qaplatform_info_log = read_file(qaplatform_info_log_path,
                                                                       qaplatform_info_log_index)
        if crawl_celery_worker_log:
            celery_worker_log_index, celery_worker_log = read_file(celery_worker_log_path, celery_worker_log_index)

        data = {
            'celery_worker_log_index': celery_worker_log_index,
            'celery_worker_log': celery_worker_log,
            'qaplatform_info_log_index': qaplatform_info_log_index,
            'qaplatform_info_log': qaplatform_info_log
        }
        return Response(status=status.HTTP_200_OK, data=data)
